package com.wtzz.police.base.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import com.wtzz.police.base.model.enums.Role;
import io.swagger.annotations.ApiModel;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static javax.persistence.ConstraintMode.NO_CONSTRAINT;

/**
 *
 */
@ApiModel("用户信息")
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "user",
       indexes = @Index(columnList = "username"),
       uniqueConstraints = {@UniqueConstraint(name = "unique_user_username", columnNames = "username")})
public class User extends AbstractAuditingEntity implements UserDetails, Serializable {

    private static final long serialVersionUID = -2849697801022922734L;
    /**
     * 账号
     */
    @Column(length = 50,  nullable = false)
    private String username;
    /**
     * 密码
     */
    @JsonProperty(access = Access.WRITE_ONLY)
    @Column
    private String password;
    /**
     * 姓名
     */
    @Column(nullable = false)
    private String fullname;
    /**
     * 联系电话
     */
    private String phone;
    /**
     * 部门
     */
    @ManyToOne
    @JoinColumn(name = "department_code", foreignKey = @ForeignKey(NO_CONSTRAINT))
    private Department department;
    /**
     * 部门名称
     */
    private String departmentName;
    /**
     * 账号类型
     */
    @Enumerated(EnumType.STRING)
    private Role role = Role.USER;
    /**
     * 状态
     */
    private boolean enabled = true;
    /**
     * 账号非锁定
     */
    private boolean accountNonLocked = true;
    /**
     * 账号非过期
     */
    private boolean accountNonExpired = true;
    /**
     * 密码未过期
     */
    private boolean credentialsNonExpired = true;

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (this.role != null) {
            List<SimpleGrantedAuthority> roles = new ArrayList<>();
            roles.add(new SimpleGrantedAuthority(this.role.name()));
            return roles;
        }
        return null;
    }

}